package com.hunanwenli.controller;
import com.alibaba.fastjson.JSON;
import com.hunanwenli.entity.*;
import com.hunanwenli.mapper.OrderMsgMapper;
import com.hunanwenli.mapper.ShopGoodsMapper;
import com.hunanwenli.service.CommodityService;
import com.hunanwenli.service.RedisService;
import com.hunanwenli.service.TokenService;
import com.hunanwenli.service.login.FeignLoginService;
import com.hunanwenli.service.userInfo.FeignUserInfoService;
import com.hunanwenli.tool.BeanUtil;
import com.hunanwenli.tool.HtmlParseUtil;
import com.hunanwenli.tool.ThreadPoolService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Http;
import lombok.extern.log4j.Log4j2;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author wanzhenyu
 * @date 2021/6/6 23:45
 */
@Controller
@ResponseBody
@Log4j2
@RequestMapping(value = "/sk")
public class    shopSeckillContrller {
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OrderMsgMapper orderMsgMapper;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    /**
     * @param time 小时
     */
    @GetMapping(value = "addDiscountGoods/{uid}/{time}/{goodName}/{goodStoke}/{goodPrice}/{goodPicture}")
    @ResponseBody
    public String addDiscountGoods(@PathVariable("uid")Long uid,
                                   @PathVariable("time") Long time,
                                   @PathVariable("goodName")String goodName,
                                   @PathVariable("goodStoke")int goodStoke,
                                   @PathVariable("goodPrice")double goodPrice,
                                   @PathVariable("goodPicture") String goodPicture){
        ShopGoods shopGoods = new ShopGoods();
        Date createDate = new Date();
        long dateTime = createDate.getTime();
        Date endDate = new Date(dateTime+60*60*1000*time);
        shopGoods.setUid(uid).setGoodname(goodName).setGoodprice(goodPrice).setVersion(0L).
                setGoodstoke(goodStoke).setCreatetime(createDate).setEndtime(endDate).setGoodPicture(goodPicture);
        commodityService.insert(shopGoods);
        Long id = shopGoods.getId();
        return addSpikeToken(id, (long) goodStoke, time * 60*60);

    }
    //@GetMapping(value = "addSpikeToken")

    public String addSpikeToken(Long shopId,Long tokenQuantit,Long time){
        if (shopId==null) {
            return "商品库存id不能为空!";
        }
        if (tokenQuantit == null) {
            return "token数量不能为空!";
        }
        ShopGoods shopGoods = commodityService.selectByPrimaryKey(shopId);
        if (shopGoods == null) {
            return "商品信息不存在!";
        }
        // 使用多线程异步生产令牌
        ThreadPoolExecutor executor = ThreadPoolService.getInstance();
        executor.execute(()->{
            createSeckillToken(shopId,tokenQuantit,time);
        });
        return "商品已上传.....";
    }

    private void createSeckillToken(Long shopId, Long tokenQuantit,Long time) {
        tokenService.createListToken(shopId,tokenQuantit,time);
    }



    @GetMapping(value = "seckill/{shopId}/{phone}")
    @HystrixCommand(fallbackMethod = "secKillFall")
    public String seckill(@PathVariable("shopId")Long shopId,@PathVariable("phone")String phone ){
        if (shopId==null) {
            return "商品库存id不能为空!";
        }
        if (phone == null) {
            return "手机号不能为空!";
        }
        ShopGoods shopGoods = commodityService.selectByPrimaryKey(shopId);
        if (shopGoods == null) {
            return "商品信息不存在!";
        }
        Object o = redisService.popList("kill"+shopId);
        if (o==null){
            log.info("抱歉商品已售空");
            return "抱歉商品已售空";
        }
        ThreadPoolExecutor executor = ThreadPoolService.getInstance();
        executor.execute(()->{
            String jsonUserInfo = redisService.get(phone);
            UserInfo userInfo = JSON.parseObject(jsonUserInfo, UserInfo.class);
            String address = userInfo.getAddress() + "-" + userInfo.getAutograph();
            OrderMsg orderMsg = new OrderMsg();
            String uuid = UUID.randomUUID().toString().replace("-","").substring(1,10);
            orderMsg.setId(uuid).setState(0).setCreateTime(new Date()).setSeckillId(shopId).
                    setUserPhone(phone).setAddress(address);
            commodityService.sendMessage(orderMsg);
        });
        return "正在抢购";
    }


    @GetMapping(value = "allGoods")
    @ResponseBody
    public String allGoods(){
        List<ShopGoods> shopGoods = commodityService.selectAllGoods();
        return JSON.toJSONString(shopGoods);
    }

    @GetMapping(value = "searchShop/{shopName}")
    @ResponseBody
    public String searchShop(@PathVariable("shopName") String shopName) {
        String redisSearch = redisService.get("search_shop" + shopName);
        if (!StringUtils.isEmpty(redisSearch)){
            return redisSearch;
        }
        String url = "https://search.jd.com/Search?keyword=" + shopName;
        List<Content> document = HtmlParseUtil.getGoodsList(url);
        String jsonString = JSON.toJSONString(document);
        redisService.put("search_shop" + shopName,jsonString,60*60*24L);
        return jsonString;
    }
    @GetMapping(value = "fastShop")
    @ResponseBody
    public String fastShop(){
        String redisSearch = redisService.get("fast_shop" );
        if (!StringUtils.isEmpty(redisSearch)){
            return redisSearch;
        }
        List<Content> contents = HtmlParseUtil.fastShop();
        String jsonString = JSON.toJSONString(contents);
        redisService.put("fast_shop",jsonString,60*60L);
        return jsonString;
    }

    @GetMapping(value = "groupShop")
    @ResponseBody
    public String groupShop(){
        String redisSearch = redisService.get("group_shop" );
        if (!StringUtils.isEmpty(redisSearch)){
            return redisSearch;
        }
        List<Content> contents = HtmlParseUtil.groupShop();
        String jsonString = JSON.toJSONString(contents);
        redisService.put("group_shop",jsonString,60*60L);
        return jsonString;
    }
    @GetMapping(value = "myOrderMsg/{phone}")
    @ResponseBody
    public String myOrderMsg(@PathVariable("phone") String phone){
        List<OrderMsg> orderMsgs = orderMsgMapper.selectListByPhone(phone);
        List<OrderMsgVo> orderMsgVos = BeanUtil.toBeanList(orderMsgs, OrderMsgVo.class);
        if (null!=orderMsgVos){
            for (OrderMsgVo orderMsgVo:orderMsgVos) {
                Long seckillId = orderMsgVo.getSeckillId();
                ShopGoods goods = shopGoodsMapper.selectByPrimaryKey(seckillId);
                if (goods!=null){
                    orderMsgVo.setGoodname(goods.getGoodname()).setGoodprice(goods.getGoodprice()).
                            setGoodPicture(goods.getGoodPicture());
                }
            }
        }
        return JSON.toJSONString(orderMsgVos);

    }
    public String secKillFall(Long shopId,String phone ){
        return "服务超时，已熔断";
    }
}

